import React, { useEffect, useState, useRef } from 'react';
import { Link, useSelector, useDispatch, history } from 'umi';
import { queryProductAll } from '@/services/store';
import { queryMyLastOrder } from '@/services/order';
import { isEmpty, storeOptionListMap } from '@/utils/common';
import { AsyncLoading, Modal } from '@/design';
import Header from '@/components/Header/Header';
import throttle from 'lodash/throttle';
import Nav from './components/nav';
import Menu from './components/menu';
import ShoppingCart from './components/shoppingCart';
import styles from './index.less';
import Share from '@/components/Share/Share';
import { Scroll, Position } from '@/components/Scroll/Scroll';


declare var window: Window & { scrollLock: boolean };
window.scrollLock = true; // 用来暂时锁住右边滚动时触发左边也自动滚动

const PIndex: React.FC = (props: any) => {
  const { braId, codeId } = props.location.query;
  const dispatch = useDispatch();
  const [loading, setLoading] = useState<boolean>(false);
  const [allMealProduct, setAllMealProduct] = useState<IAllMealProductProps>();
  const [mylastOrder, setMylastOrder] = useState<any>({});
  const token = localStorage.getItem('TOKEN');


  const navRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  const [shoppingVisiable, setShoppingVisiable] = useState<boolean>(false);
  const [shareVisible, setShareVisible] = useState<boolean>(false);
  const { codeDetail, storeOptionList } = useSelector((state: any) => state.store);

  const { currentstore } = useSelector((state: any) => state.currentstore);

  const { cartList } = useSelector((state: any) => state.cartList);

  const bindScroll = () => {
    const nav = navRef.current as HTMLDivElement;
    const menu = menuRef.current as HTMLDivElement;
    if (isEmpty(nav) || isEmpty(menu)) return
    const menuItems: any = [...menu?.children[0].getElementsByClassName('menuItem')];
    const navItems: any = [...nav?.children[0].getElementsByTagName('li')];
    let navHeight = navItems[0]?.offsetHeight; //左边一个item的高度

    const throttleScroll = throttle(() => {
      // 监听右边每类菜单，
      menuItems.forEach((item: HTMLDivElement, index: number) => {
        const menuTop = item.getBoundingClientRect().top;
        // 当这类菜单滚到顶部时，左边会高亮对应的导航，并且左边导航滚到相应视图内
        if (menuTop <= 0 && window.scrollLock) {
          // 这里改成filter
          navItems.forEach((navItem: HTMLDivElement) => navItem.classList.remove('nav-active'));
          navItems[index].classList.add('nav-active');

          // 将左边滚到视图内
          // nav.scrollTo(0, navHeight*index);
        }
      })
    }, 300);

    menu.addEventListener('scroll', throttleScroll, false);
  }

  //查詢全部菜品
  const fetchAllMealProduct = async () => {
    setLoading(true);
    let result = await queryProductAll();
    getProducts(result?.data);
    setLoading(false);
    bindScroll();
  }

  const tapNavItem = (index: number) => {
    const nav = navRef.current as HTMLDivElement;
    const menu = menuRef.current as HTMLDivElement;
    // 數據還沒出來返回
    if (isEmpty(nav) || isEmpty(menu)) return
    const menuItems: any = [...menu?.children[0].getElementsByClassName('menuItem')];
    const navItems: any = [...nav?.children[0].getElementsByTagName('li')];
    // 这里改成filter
    navItems.forEach((navItem: HTMLDivElement) => navItem.classList.remove('nav-active'));
    navItems[index].classList.add('nav-active');

    window.scrollLock = false;
    setTimeout(() => window.scrollLock = true, 400);
    let h = 0;
    menuItems.forEach((item: HTMLDivElement, menuIndex: number) => {
      if (menuIndex < index) {
        h = h + item?.offsetHeight;
      }
    })
    menu.scrollTo(0, h);
  }

  //查询菜品
  useEffect(() => {
    fetchAllMealProduct();
  }, []);

  // 消費者掃碼是否進入詳情頁
  useEffect(() => {
    // 不是先吃后付的情况查一下 避免很下多单
    if (storeOptionListMap(storeOptionList).get('is_first_eat') !== '1') {
      fetchMylastOrder();
    }

  }, [codeDetail.tableCode, token]);

  useEffect(() => {
    const orderStatusTypes = new Map([['unconfirm', '等待確認訂單'], ['nopay', '未支付'], ['invalid', '已取消'], ['confirmed', '已確認'], ['payed', '已支付']]);
    if (!isEmpty(mylastOrder) && mylastOrder !== '沒有訂單') {
      if (mylastOrder.orderStatus !== 'payed') {
        Modal.confirm({
          content: `你有${orderStatusTypes.get(mylastOrder.orderStatus)}的订单，是否進入詳情`,
          shake: true,
          onConfirm: () => {
            history.push(`/orderdetail?orderNo=${mylastOrder.orderId}`)
          }
        })
      }
    }
  }, [mylastOrder])


  const fetchMylastOrder = async () => {
    if (isEmpty(token)) return;
    let param = {
      buyerCode: token,
      tableCode: codeDetail.tableCode
    }
    let result = await queryMyLastOrder(param);
    if (!result || !result.data) return false;
    setMylastOrder(result.data);
  }

  //获取门店的详情
  useEffect(() => {
    fetchCurrentStoreDetail();
  }, [braId, codeId]);

  // 当前的braId 和详情的不一样 就直接清空 
  useEffect(() => {
    if (braId !== currentstore.braId) {
      clearCartList();
    }
  }, [currentstore])

  //二维码详情
  useEffect(() => {
    fetchCodeDetail()
  }, [])

  useEffect(() => {
    setShoppingVisiable(cartList.length ? true : false);
  }, [cartList.length])

  useEffect(() => {
    fetchStoreOptionList()
  }, [])

  // 獲取店家的所有設置
  const fetchStoreOptionList = () => {
    dispatch({
      type: 'store/fetchStoreOptionList'
    })
  }

  const clearCartList = () => {
    dispatch({
      type: 'cartList/clearCartList',
    })
  }

  const fetchCurrentStoreDetail = async () => {
    !isEmpty(braId) && localStorage.setItem('BRAID', braId);
    !isEmpty(codeId) && localStorage.setItem('CODEID', codeId);
    let paramBraId = braId || localStorage.getItem('BRAID')
    dispatch({
      type: 'currentstore/fetchCurrentStoreDetail',
      payload: {
        braId: paramBraId
      }
    });
  }

  // 处理接口返回的列表
  const getProducts = (allMealProduct: IAllMealProductProps) => {
    if (!isEmpty(allMealProduct)) {
      let tempArr = allMealProduct.categoryList;
      let hotSaleList = allMealProduct.hotSaleList;
      tempArr.unshift({
        braId: hotSaleList[0]?.braId,
        categoryId: 'hot',
        categoryName: '人氣熱賣',
        productList: hotSaleList
      })
      setAllMealProduct({
        categoryList: tempArr,
        hotSaleList
      })
    }
  }

  const countOccurrences = (arr: any) => arr.reduce((a: any, v: any) => (a + v.productQuantity), 0);

  /* 查詢二维码详情 */
  const fetchCodeDetail = () => {
    dispatch({
      type: 'store/fetchCodeDetail'
    })
  }

  const isTakeout = () => {//是否是預約外帶和到點外帶
    const { diningWay } = codeDetail;
    return diningWay === 'takeout' || diningWay === 'togoBespeak' || diningWay === 'togo' || diningWay === 'togoCash';
  }

  /** 滚动监听 */
  const handlePageScroll = (pos: Position) => {
    console.log("🚀 ~ file: index.tsx ~ line 225 ~ handlePageScroll ~ pos", pos)
  }

  return (<>
    {loading ? <AsyncLoading /> : <div className={styles.store_page}>
      {/* <div className={styles.store_header_hidden}></div>
      <div className={styles.store_header_wrap}>
        <Header store onShare={() => { setShareVisible(true) }}>
          <h3>{currentstore?.braName}</h3>
        </Header>
        <div className={styles.search}>
          <Link className={styles.store_search} to="/search">
            <label htmlFor="search_input">請輸入菜品名稱</label>
            <input id='search_input' type="text" disabled />
          </Link>
          {!isTakeout() ? <button className={styles.call_btn} >呼叫</button> : null}
          <a className={styles.order_icon} href='/orderlist'></a>
        </div>
      </div> */}
      <div className={styles.store_header}> 
        <span>tableCode</span>
        <span>搜索</span>
      </div>
      <div className={`${styles.goods_wrap}`}>
        <div className={styles.content}>
          <div>
            <Nav navRef={navRef} tapNavItem={tapNavItem} categoryList={allMealProduct?.categoryList || []} />
            <Menu menuRef={menuRef} categoryList={allMealProduct?.categoryList || []} />
          </div>
         
        </div>
        {shoppingVisiable && <div className={styles.hasCartList}></div>}
        <ShoppingCart shoppingVisiable={shoppingVisiable} num={countOccurrences(cartList)} />
        <Share title={currentstore.braName} visible={shareVisible} onClose={() => setShareVisible(false)} />
      </div>
      <a className={styles.store_footer} href='http://m.icashcow.ai/'>Powered by ume</a>
      <div className={styles.empty_store_footer}></div>
    </div>}
  </>
  )
};

export default PIndex;
